package com.example.message2;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

	private EditText mEmailView;
	private EditText mPasswordView;
	static final String EXTRA_MESSAGE="";
    static final String EXTRA_MESSAGE2=""; 
	String loginStatus="not";
	private static final String PHP_REG = "http://softeng.cs.uwosh.edu/students/cs342g2/php/login.php";
	private static final String[] DUMMY_CREDENTIALS = new String[] {
		"foo@example.com:hello", "bar@example.com:world" };

/**
 * The default email to populate the email field with.
 */
public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";

/**
 * Keep track of the login task to ensure we can cancel it if requested.
 */
//private UserLoginTask mAuthTask = null;

/**
 * URL to connect to the cloud server
 */
private static final String PHP_URL = "http://softeng.cs.uwosh.edu/students/cs342g2/php/login.php";


// Values for email and password at the time of the login attempt.
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mEmailView = (EditText) findViewById(R.id.username);
		
		mPasswordView = (EditText) findViewById(R.id.password);
		
	 
		
		findViewById(R.id.registerBtn2).setOnClickListener(			 
                new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                        	MainActivity.this.finish();
                                Intent myIntent = new Intent(MainActivity.this, register.class); 
                                myIntent.putExtra(EXTRA_MESSAGE, "false");
                                startActivityForResult(myIntent, 0);
                        }
                });
		
		findViewById(R.id.sign_in_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
								//tryRegister(username, password);
						String user = mEmailView.getText().toString();
						String password = mPasswordView.getText().toString();

						View focusView = null;
						boolean cancel = false;
						
						StrictMode.ThreadPolicy policy = new 
						StrictMode.ThreadPolicy.Builder().permitAll().build();
					    StrictMode.setThreadPolicy(policy);
					    
					    HttpClient httpclient = new DefaultHttpClient(); 
			       	 	HttpPost httppost = new HttpPost( "http://softeng.cs.uwosh.edu/students/cs342g2/php/login.php");
			       	 	try { // Add your data  
			       	 		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			       	 		nameValuePairs.add(new BasicNameValuePair( "uid", user)); 
			       	 		nameValuePairs.add(new BasicNameValuePair( "password", password)); 
			       	 		httppost.setEntity(new UrlEncodedFormEntity( nameValuePairs)); 
			       		 // Execute HTTP Post Request 
			       	 		HttpResponse response = httpclient.execute(httppost); 
			       	 		String result = EntityUtils.toString(response.getEntity()); 
			       	 		if (!result.equals("Failed")) { 
			       	 			Context context = getApplicationContext(); 
			       	 			Toast toast = Toast.makeText(context, result, Toast.LENGTH_LONG); 
			       	 			toast.show();
			       	 			int id=Integer.parseInt(user);
			       	 			changeUser(id);
			       	 			changePassword(password);
			       	 			changeLastRead(Integer.parseInt(result));
			       	 			Intent myIntent = new Intent(MainActivity.this, AndroidXMLParsingActivity.class);
			       	 			startActivity(myIntent);
			       	 			//finish();
			       	 		} 
			       	 		
			       	 		//new update().execute(user); changeUser(user);
			      	 			
			       	 		Context context = getApplicationContext(); 
		       	 			Toast toast = Toast.makeText(context, result, Toast.LENGTH_LONG); 
		       	 			toast.show(); 
			       	 		
			       	 		 
			       
			       	 	} catch (ClientProtocolException e) { // TODO Auto-generated catch block 
			       			 
			       	 	} catch (IOException e) { // TODO Auto-generated catch block } }
			       	 }
				//}
					//else{Toast.makeText(getApplicationContext(), "cant connect", Toast.LENGTH_LONG).show();}		
					    					    
						
			         }

					private void startActivityFor(Intent myIntent) {
						// TODO Auto-generated method stub
						
					}
                });
	}
			
	//@Override
	//public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.main, menu);
		//return true;
	//}
    
	private void tryRegister(String username, String password) {

		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(
				//"http://softeng.cs.uwosh.edu/students/kempk79/functions.php");
		"http://http://softeng.cs.uwosh.edu/students/shulsj15/test/testdbconnection/login.php");
		try {
			// Add your data
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
					4);
			nameValuePairs.add(new BasicNameValuePair(
					"register", "true"));
			nameValuePairs.add(new BasicNameValuePair(
					"username", username));
			nameValuePairs.add(new BasicNameValuePair(
					"password", password));
			nameValuePairs.add(new BasicNameValuePair(
					"confpassword", password));
			httppost.setEntity(new UrlEncodedFormEntity(
					nameValuePairs));

			// Execute HTTP Post Request
			HttpResponse response = httpclient
					.execute(httppost);
			String result = EntityUtils.toString(response
					.getEntity());
			//(result.equals("Failure")) {
				Context context = getApplicationContext();
				Toast toast = Toast.makeText(context, result,
						400);
				toast.show();
			//} //else {
				//new update().execute(username);
				//changeUser(username);
				
			//}

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}
	}
	
	
    @Override

    protected void onResume(){
            super.onResume();
            Intent i = getIntent();
            loginStatus = i.getStringExtra(EXTRA_MESSAGE2);
    }

    public void changeLastRead(int lastRead){
    	SharedPreferences settings = getSharedPreferences("preferences", 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt("lastRead", lastRead);

        // Commit the edits!
        editor.commit();
                     
    }
    public void changeUser(int ID){
    	SharedPreferences settings = getSharedPreferences("preferences", 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt("curUser", ID);

        // Commit the edits!
        editor.commit();
               
    }
    public void changePassword(String password){
    	SharedPreferences settings = getSharedPreferences("preferences", 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("curPassword", password);

        // Commit the edits!
        editor.commit();
        
    }
}
